/*
 * @Date: 2024-01-10 09:39:02
 * @LastEditors: lyx
 * @LastEditTime: 2024-01-12 15:28:07
 * @FilePath: \chlor-alkali-cloud-mobile-end\src\components\NoTokenInterceptor\index.tsx
 * @Description:
 */
import { useGlobalData } from "@/store/index";
import { getRandomString, toLogin } from "@/utils/common";
import { View } from "@tarojs/components";
import Taro, { getCurrentInstance } from "@tarojs/taro";
import React, { useEffect } from "react";
import { last } from "lodash";
import SupRequest from "@/utils/api";
function NoTokenInterceptor() {
  const { router } = getCurrentInstance();
  const { params, path } = router || {};
  const { code = "" } = params || {};
  const { isLogin, setIsLogin } = useGlobalData();
  console.log("当前页面 router", router);
  console.log("当前页面 Taro.getCurrentPages()", Taro.getCurrentPages());
  const currentPagesList = Taro.getCurrentPages();

  const goToLogin = async (rCode = "") => {
    const res = await SupRequest({
      url: `/adapter/sup-adapter/feishu/auth/getAccessToken?code=${rCode}`,
      method: "GET",
    });
    console.log("feishu res", res);
    const { code = "00000", content = {} } = res;

    if (code === "00000") {
      const { additional } = content;
      // TODO: 这边需要调用  适配器接口后重置

      Taro.setStorageSync("token", additional);
      Taro.setStorageSync("userInfo", content);
      setIsLogin(true);
    }
  };

  useEffect(() => {
    console.log("当前页面 path", path);
    console.log("当前页面 isLogin", isLogin);
    if (code) {
      console.log("登录预授权码code", code);

      goToLogin(code);
    } else if (!isLogin) {
      setIsLogin(false);
      const cPage = last(currentPagesList);
      console.log("cPage", cPage);
      toLogin(cPage?.route ?? "");
    }
  }, [code, isLogin]);

  return <View />;
}

export default NoTokenInterceptor;
